﻿using IISLogAnalyzer.Common;
using System.Data;
using System.IO;
using System.Windows;

namespace IISLogAnalyzer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn("row", typeof(long)));
            var path = txtFilePath.Text;
            using (var file = File.Open(path, FileMode.Open, FileAccess.Read))
            using (var sr = new StreamReader(file))
            {
                var s = "";
                int maxRow = 10;
                while (maxRow > 0)
                {
                    s = sr.ReadLine();
                    if (s.StartsWith("#Fields"))
                    {
                        var columns = s.Substring(s.IndexOf("#Fields: ") + "#Fields: ".Length).Split(' ');
                        foreach (var item in columns)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                dataTable.Columns.Add(new DataColumn(item, typeof(string)));
                            }
                        }
                        break;
                    }
                    maxRow--;
                }

                long rowN = 0;
                while (!sr.EndOfStream)
                {
                    s = sr.ReadLine();
                    if (!s.StartsWith("#"))
                    {
                        var row = dataTable.NewRow();
                        row[0] = rowN;
                        var cells = s.Split(' ');
                        for (var i = 1; i < dataTable.Columns.Count; i++)
                        {
                            row[i] = cells[i -1];
                        }
                        rowN++;
                        dataTable.Rows.Add(row);
                    }
                }
            }

            //dataGrid.AutoGenerateColumns = true;
            //dataGrid.ItemsSource = dataTable.AsDataView();

            SqlConnectionExtension.WriteToDataBase(dataTable, System.IO.Path.GetFileNameWithoutExtension(path), false, false, new string[] { "row" });

            //using (var con = new SqlConnection("Data Source=172.22.85.32;Initial Catalog=IIS_20230109;Persist Security Info=True;User ID=portal;Password=Dic@0628db"))
            //{
            //    con.Open();
            //    con.BulkCopy(dataTable, 100000, System.IO.Path.GetFileNameWithoutExtension(path));
            //    con.Close();
            //}
        }
    }
}
